<style scoped>
    .layout {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        border: 1px solid #d7dde4;
        border-radius: 4px;
        overflow: hidden;
        width: 100%;
        height: 100%;
    }

    .layout-footer-center {
        text-align: center;
        font-size: 16px;
        padding: 10px;
    }

</style>
<style>
    .ivu-card-bordered {
        border: 0px !important;
    }

    .blueScreen .ivu-modal .ivu-modal-body {
        padding: 0px;
    }

</style>
<template>
    <Layout class="layout" @click.native="countdownReset()" @mousedown.native="touchstart">
        <Sider hide-trigger style="background-color: #f8f8f9;" width="250">
            <div style="display:flex;justify-content:space-around;align-items:center;flex-direction:column;padding: 30px;height: 90%;">
                <img src="../images/logo.png" width="200">
            </div>
            <div style="display:flex;justify-content:center;height:10%;">
                <Button type="primary" v-on:click="showAbout()"
                        style="width:200px;height: 45px;">
                    <p style="font-size: 18px;">
                        <Icon type="md-jet"/>
                        关于系统
                    </p>
                </Button>
            </div>
        </Sider>
        <Layout>
            <Content style="height: 100%;padding: 2%" :style="this.$root.background">
                <p style="text-align:right;font-size: 14px;">本系列软件软著登记号 2020SR0066967(设备控制) 2020SR0066718(用户交互)
                    <br/> 本自助打印设备专利号 ZL 202020290675.5</p>
                <Row type="flex">
                    <Col span="24"
                         style="display:flex;justify-content:flex-start;flex-direction:column;padding:50px;">
                        <p style="margin: 10px;font-size: 46px">点墨自助打印设备 <span style="font-size: 18px;">{{$root.version}}</span>
                        </p>
                        <Row type="flex" style="margin: 10px">
                            <Col span="12">
                                <Card v-on:click.native="showClause('print')" :style="background1"
                                      style="margin-right: 20px;">
                                    <div style="display:flex;justify-content: flex-end;align-items: flex-end;flex-direction:row;height: 328px; padding: 10px;">
                                        <img src="../images/printer.svg" style="margin-right:30px;" width="100"
                                             height="100">
                                        <div style="text-shadow:1px 1px 3px #f8f8f9;">
                                            <p style="font-size: 32px;">文 件 打 印</p>
                                            <p style="font-size: 22px;">Print</p>
                                        </div>
                                    </div>
                                </Card>
                            </Col>
                            <Col span="12">
                                <Card v-on:click.native="showClause('scan')" :style="background2"
                                      style="margin-bottom: 20px;">
                                    <div style="display:flex;justify-content: flex-end;align-items: flex-end;flex-direction:row;height: 138px; padding: 10px;">
                                        <img src="../images/scanner.svg" style="margin-right:30px;" width="100"
                                             height="100">
                                        <div style="text-shadow:1px 1px 3px #f8f8f9;">
                                            <p style="font-size: 32px;">文 件 扫 描</p>
                                            <p style="font-size: 22px;">Scan</p>
                                        </div>
                                    </div>
                                </Card>
                                <Card v-on:click.native="showClause('copy')" :style="background3">
                                    <div style="display:flex;justify-content: flex-end;align-items: flex-end;flex-direction:row;height: 138px; padding: 10px;">
                                        <img src="../images/copy-machine.svg" style="margin-right:30px;" width="100"
                                             height="100">
                                        <div style="text-shadow:1px 1px 3px #f8f8f9;">
                                            <p style="font-size: 32px;">文 件 复 印</p>
                                            <p style="font-size: 22px;">Copy</p>
                                        </div>
                                    </div>
                                </Card>
                            </Col>
                        </Row>

                        <v-exception ref="exceptionModel"></v-exception>
                        <Modal v-model="adminModel" width="720px" >
                            <p slot="header" style="color:#2b85e4;text-align:center">
                                <Icon type="ios-information-circle"></Icon>
                                <span>管理员模式</span>
                            </p>
                            <div style="display: flex;align-items:center;flex-direction:column">
                                <img src="../images/admin.png" width="120">
                                <p style="text-align:center;font-size: 18px;margin: 10px">
                                    请选择需要执行的操作（设备ID:{{this.$root.deviceID}}）</p>
                                <div style="flex-direction:row">
                                    <Button type="warning" size="large" @click="exitAndShutdown" style="margin: 10px">
                                        立刻关闭设备电源(60s倒计时)
                                    </Button>
                                    <Button type="warning" size="large" @click="exitAndRebooting" style="margin: 10px">
                                        立刻重启设备(60s倒计时)
                                    </Button>
                                    <Button type="warning" size="large" @click="exit" style="margin: 10px">
                                        立刻退出MOTA控制系统
                                    </Button>
                                    <Button type="warning" size="large" @click="stopServer" style="margin: 10px">
                                        立刻停用设备
                                    </Button>
                                </div>
                            </div>
                        </Modal>
                        <Modal v-model="adminLoginModel" width="720px">
                            <p slot="header" style="color:#2b85e4;text-align:center">
                                <Icon type="ios-information-circle"></Icon>
                                <span>管理员模式</span>
                            </p>
                            <div style="display: flex;align-items:center;flex-direction:column">
                                <img src="../images/admin.png" width="120">
                                <p style="text-align:center;font-size: 18px;margin-top: 10px">
                                    请输入管理员密码（设备ID:{{this.$root.deviceID}}）</p>
                                <p style="margin-bottom: 10px">若您非墨拓设备管理员请立刻退出本页面</p>
                                <Input v-model="password" size="large" placeholder="请输入本机密码"
                                       style="width: 300px;margin-bottom: 20px;"/>
                                <v-keyboard v-on:updatekey="getPassword"></v-keyboard>
                            </div>
                            <div slot="footer">
                                <Button type="success" size="large" @click="checkPassword()">确认
                                </Button>
                            </div>
                        </Modal>


                        <Drawer title="内容审查与免责声明" :closable="false" v-model="statement" width="650">
                            <!--<video width="400" height="300" controls id="video" autoplay></video>-->
                            <div style="font-size: 16px; overflow: auto;height: 90%">
                                <p style="color:#f60;text-align:center;">第一部分</p>
                                <div style="text-indent: 2em;">
                                    <p>
                                        点墨会采取必要的技术措施，确保侵权内容或违规内容不能在点墨设备上印刷或留存。若点墨发现您打印、复印、扫描的文件、资料、书籍（包括但不限于列举的材料）内容存在或可能存在侵犯任何第三方知识产权或其他合法权益的情形，或被认定或可能被认定为违规内容（定义见下文），点墨有权在不经事先通知的情况下随时终止该侵权或违规内容的打印操作，并对证据进行留存，同时保留移交司法机关处理的权利。
                                    </p>
                                    <br/>
                                    <p>
                                        若点墨发现您反复打印侵权内容或违规内容，则点墨有权随时停止为您提供服务，并采取包括移交司法机关处理等各种措施.
                                    </p>
                                    <br/>
                                    <p>
                                        违法信息是指违背《中华人民共和国宪法》和《全国人大常委会关于维护互联网安全的决定》、《互联网信息服务管理办法》所明文严禁的信息以及其它法律法规明文禁止传播的各类信息。对于以下内容（统称“违规内容”），点墨必须予以终止操作并做证据留存处理：</p>
                                    <br/>
                                    <p>
                                        a) 反对宪法所确定的基本原则的；b) 危害国家安全，泄露国家秘密，颠覆国家政权，破坏国家统一的；c) 损害国家荣誉和利益的；d)
                                        煽动民族仇恨、民族歧视，破坏民族团结的；e)
                                        破坏国家宗教政策，宣扬邪教和封建迷信的；f) 散布谣言，扰乱社会秩序，破坏社会稳定的；g) 散布淫秽、色情、赌博、暴力、凶杀、恐怖或者教唆犯罪的；h)
                                        侮辱或者诽谤他人，侵害他人合法权益的；i) 含有法律、行政法规禁止的其它内容的。
                                    </p>
                                </div>

                                <div style="text-indent: 2em;"><p style="color:#f60;text-align:center">第二部分</p>
                                    <p>
                                        用户承诺对其上传或者使用点墨设备打印的所有信息、内容（即属于《中华人民共和国著作权法》规定的作品，包括但不限于文字、图片等）均享有完整的知识产权，或者已经得到相关权利人的合法授权。
                                    </p>
                                    <br/>
                                    <p>
                                        当第三方认为用户通过点墨印刷的印刷物或通过点墨设备制作的电子书侵犯其权利时，用户同意点墨提供相关打印历史记录供相关机构调查取证，给涉嫌侵权的用户带来的任何损失，点墨不承担任何法律责任。如用户在使用点墨设备时违反上述任何规定，点墨有权采取一切必要的措施（包括但不限于终止用户使用点墨设备的权利、提供相关用户信息等）以减轻用户不当行为而造成的影响。由此给该用户带来的任何损失，点墨不承担任何法律责任。
                                    </p>
                                </div>

                                <div style="text-indent: 2em;"><p style="color:#f60;text-align:center">第三部分</p>
                                    <p>
                                        任何由于黑客攻击、电脑病毒侵入或政府管制而造成的暂时性网络服务终止或设备关闭，除正在进行的付费打印任务将退还费用外，对免费打印与其他业务点墨不承担任何法律责任。
                                    </p>
                                    <p>
                                        对免责声明的解释、修改及更新权均属于点墨所有。
                                    </p>
                                </div>
                            </div>

                            <div class="drawer-footer">
                                <Button @click="allow" type="success" size="large"
                                        icon="md-print"
                                        style="width:500px;height: 45px;"><p style="font-size: 18px;">我完全理解上述内容并接受 /
                                    Accept</p>
                                </Button>
                            </div>
                        </Drawer>
                        <Modal v-model="systemError" :footer-hide="true" :closable="false" :mask-closable="false"
                               width="800" class="blueScreen">
                            <div style="color: white;background-color: blue;padding: 20px;">
                                <h1>
                                    <Icon type="ios-bug"/>
                                    程序崩溃 / CRASH
                                </h1>
                                <Divider></Divider>
                                <h2>这是设备陷入完全崩溃状态的最后通知!</h2>
                                <br/>
                                <h2>自助打印设备客户端程序的心跳已经丢失，这可能是由于程序崩溃导致的</h2>
                                <h2>请联系点墨运维人员(189-5970-3965)对设备进行重新启动</h2>
                                <Divider></Divider>
                                <h3>This is the last notification that the device is in a complete crash state!</h3>
                                <br/>
                                <h3>The heartbeat of the self-service printing device client program has been lost,
                                    which may be caused by the program crash.</h3>
                                <h3>Please contact the operation and maintenance personnel of dianmo (133-0535-6699) to
                                    restart the equipment.</h3>
                            </div>
                        </Modal>
                    </Col>
                </Row>
            </Content>
            <Footer>
                <p class="layout-footer-center">2018-2020 &copy; Changsha Dianmo Culture Media Co., Ltd 长沙点墨文化传媒有限公司</p>
                <v-countdownButton ref="countdown"
                                   style="position: absolute; right: 10px; bottom:10px;"></v-countdownButton>
            </Footer>
        </Layout>
    </Layout>
</template>

<script>
    import * as axios from "axios";
    import ExceptionModel from '../components/ExceptionModel.vue';
    import CountdownButton from '../components/CountdownButton.vue';
    import Keyboard from '../components/Keyboard.vue';

    export default {
        components: {
            'v-exception': ExceptionModel,
            'v-countdownButton': CountdownButton,
            'v-keyboard': Keyboard,
        },
        data() {
            return {
                statement: false,
                routerPath: "",
                type: "",
                triggerCount: 0,
                adminLoginModel: false,
                adminModel: false,
                password: "",
                background1: {
                    backgroundImage: "url(" + require("../images/background1.png") + ")",
                    backgroundPosition: "bottom",
                    backgroundSize: "cover",
                },
                background2: {
                    backgroundImage: "url(" + require("../images/background2.png") + ")",
                    backgroundPosition: "bottom",
                    backgroundSize: "cover",
                },
                background3: {
                    backgroundImage: "url(" + require("../images/background3.png") + ")",
                    backgroundPosition: "bottom",
                    backgroundSize: "cover",
                },
                systemError: false,
                mediaStream: null,
                mediaRecorder: null,
                chunks: [],
            }
        },
        mounted() {
            this.$refs.countdown.countDownStart(60, "/Carousel", false);
            this.$root.printUserMark = this.randomWord(false, 15);
            this.getBaseSetting();
            this.attachMedia();
        },
        destroyed(){
            this.upload();
        },
        methods: {
            getMediaStream() {
                return navigator
                    .mediaDevices
                    .getUserMedia({
                        audio: false,
                        video: true
                    });
            },
            attachMedia() {
                this.getMediaStream()
                    .then(stream => {
                        //document.querySelector('#video').srcObject = stream;
                        this.mediaStream = stream;
                        this.record();
                    })
                    .catch(err => alert(`${err.name}: ${err.message}`));
            },
            record() {
                this.mediaRecorder = new MediaRecorder(this.mediaStream, {mimeType: "video/webm"});

                this.mediaRecorder.addEventListener('dataavailable', e => {
                    this.chunks.push(e.data);
                });
                this.mediaRecorder.start(10);
            },
            stopRecord() {
                this.mediaRecorder.stop();
                this.mediaStream.getTracks()[0].stop();
            },
            upload() {
                this.stopRecord();
                let blob = new Blob(this.chunks, {type: "video/webm"});
                this.chunks = [];

                const formData = new FormData();
                formData.append('uploadFile', blob, this.$root.printUserMark + '.webm');

                axios({
                    method: 'post',
                    url: 'http://localhost:8999/uploadSurveillanceVideo',
                    data: formData,
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(res => {
                    console.log('上传成功！')
                }).catch(err => {
                    console.log('上传失败！')
                })
            },
            countdownReset() {
                this.$refs.countdown.countdownReset(60);
            },
            randomWord(randomFlag, min, max) {
                let str = "";
                let range = min;
                let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

                // 随机产生
                if (randomFlag) {
                    range = Math.round(Math.random() * (max - min)) + min;
                }
                for (let i = 0; i < range; i++) {
                    let pos = Math.round(Math.random() * (arr.length - 1));
                    str += arr[pos];
                }
                return str;
            },

            getBaseSetting() {
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/getBaseSetting',
                }).then((response) => {
                    let responseData = response.data;
                    if (responseData.state === 'SUCCESS') {
                        if (responseData.code === "1") {
                            let settingList = JSON.parse(responseData.msg);
                            this.$root.serverUrl = settingList["ServerUrl"];
                            this.$root.deviceID = settingList["DeviceID"];
                            this.$root.websocketUrl = settingList["ServerUrl"].replace(/http/, "ws");
                            this.password = settingList["Password"];
                            this.$root.userUploadPrintFilePageUrl = settingList["UserUploadPrintFilePageUrl"];
                            this.$root.userDownloadScanFilePageUrl = settingList["UserDownloadScanFilePageUrl"];
                            this.$root.userErrorRefundPageUrl = settingList["UserErrorRefundPageUrl"];
                        }
                    }
                }).catch((reason) => {
                    clearInterval(this.$root.countdownClock);
                    this.systemError = true;
                });
            },

            showClause(type) {
                this.statement = true;
                this.type = type;
            },
            allow() {
                clearInterval(this.countdownClock);
                this.$router.push({
                    name: this.type == 'print' ? 'UploadFile' : 'Scan',
                    params: {
                        //转跳并传递参数设备路径参数
                        type: this.type,
                    }
                });
                console.log(this.type);
                this.$root.mode = this.type;
            },

            touchstart(e) {
                if (this.triggerCount == 4) {
                    this.adminLoginModel = true;
                }
                let triggerRange = 100;
                if (e.clientY < triggerRange && e.clientX < triggerRange) {
                    this.triggerCount = 1;
                }
                if (e.clientY < triggerRange && document.documentElement.clientWidth - e.clientX < triggerRange && this.triggerCount == 1) {
                    this.triggerCount = 2;
                }
                if (document.documentElement.clientHeight - e.clientY < triggerRange && document.documentElement.clientWidth - e.clientX < triggerRange && this.triggerCount == 2) {
                    this.triggerCount = 3;
                }
                if (document.documentElement.clientHeight - e.clientY < triggerRange && e.clientX < triggerRange && this.triggerCount == 3) {
                    this.triggerCount = 4;
                }
            },

            showAbout() {
                this.$Modal.info({
                    title: "关于",
                    content: `<img src="` + require("../images/about.png") + `" width="100%"/>`,
                    width: 900,
                });
            },

            getPassword(val) {
                this.password = val;
            },
            checkPassword() {
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/getPassword',
                }).then((response) => {
                    if (response.data == this.password) {
                        this.adminLoginModel = false;
                        this.adminModel = true;
                    } else {
                        this.$Modal.confirm({
                            title: '密码错误',
                            content: '请核对您的密码，确保输入正确！',
                            okText: '确认',
                            onOk: () => {
                                this.$Modal.remove();
                            },
                        });
                    }
                }).catch((reason) => {
                    this.closeAllModel();
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                });
            },
            exit() {
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/exit',
                })
            },
            exitAndShutdown() {
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/exitAndShutdown',
                })
            },
            exitAndRebooting() {
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/exitAndRebooting',
                })
            },
            stopServer() {
                this.closeAllModel();
                this.$refs.exceptionModel.openExceptionModel("ADMIN", "STOP SERVER - 管理员终止了本台设备运行", 10001, "STOP", true);
            },
            closeAllModel() {
                this.adminLoginModel = false;
                this.adminModel = false;
            }
        }
    }
</script>